import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLogout } from '@/api';
import { setToken, getToken, removeToken } from '@/utils/token';
const state = {
    code: '',
    token: getToken(),
    userInfo: {},
};
const mutations = {
    GETCODE(state, code) {
        state.code = code
    },
    USERLOGIN(state, token) {
        state.token = token;
    },
    USERINFO(state, data) {
        state.userInfo = data;
    },
    CLEAR(state) {
        state.token = '';
        state.userInfo = {};
        removeToken();
    }
};
const actions = {
    async getCode(context, phone) {
        let result = await reqGetCode(phone);
        if (result.code == 200) {
            context.commit('GETCODE', result.data);
            return 'ok';
        } else {
            return new Error('验证码发送失败')
        }
    },
    async userRegister(context, userInfo) {
        let result = await reqUserRegister(userInfo);
        if (result.code == 200) {
            return 'ok';
        } else {
            return new Error('注册失败')
        }
    },
    async userLogin(context, data) {
        let result = await reqUserLogin(data);
        //服务器下发token,用户的唯一标识符
        //将来经常通过token找服务器要用户信息
        if (result.code == 200) {
            context.commit('USERLOGIN', result.data.token);
            setToken(result.data.token);
            return 'ok';
        } else {
            return Promise.reject(new Error('登录失败'))
        }
    },
    async getUserInfo(context) {
        //获取用户信息
        let result = await reqUserInfo();
        if (result.code == 200) {
            context.commit('USERINFO', result.data);
            return 'ok';
        } else {
            // return Promise.reject(new Error('获取用户信息失败'))
        }
    },
    async userLogout(context) {
        //到这里只是把服务器里面的token清楚了
        let result = await reqLogout();
        if (result.code == 200) {
            context.commit('CLEAR'); // 不能直接操作state,让mutation去处理
            return 'ok';
        } else {
            return Promise.reject(new Error('退出登录失败'))
        }
    }
};
const getters = {};

export default {
    state,
    mutations,
    actions,
    getters,
}